<?php

namespace app\admin\controller;

use app\admin\model\Admin as adminModel;
use app\LdapBase;
use app\admin\controller\Permissions;
use \think\Db;

class Ldapuser extends Permissions {

    public function userList() {
        $ldap = new LdapBase();
        $userList = $ldap->userList();

        $this->assign('userList', $userList);
        return $this->fetch();
    }

    public function oldUserList() {
        $ldap = new LdapBase();
        $userList = $ldap->oldUserList();

        $this->assign('userList', $userList);
        return $this->fetch();
    }

    public function publish() {
        $model = new adminModel();
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        $post = $this->request->request();

        $ldap = new LdapBase();
        $groupList = $ldap->groupList();
//        print_r($groupList);
        $this->assign('groupList', $groupList);

        if (!empty($id)) {
            //是修改操作提交
            if ($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['second_name', 'require', '账号为必填字段'],
                    ['display_name', 'require', '姓名为必填字段'],
                    ['email', 'require|email', 'email为必填字段'],
                    ['group', 'require', '请选择分组']
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }
//                print_r($post);
//                exit;                

                $unixTimeDays = floor(time() / 86400);

                $info['gidnumber'][0] = "0";
                $info['sn'][0] = $post['id'];
                $info['givenName'][0] = $post['id'];
                $info['displayName'][0] = $post['display_name'];
                $info['uid'][0] = $post['id'];
                $info['homedirectory'][0] = $post['id'];
                $info['mail'][0] = $post['email'];
                $info['cn'][0] = $post['display_name'];
                $info['description'][0] = $post['display_name'];
//                $info['gecos'][0] = $post['id'];

                if (!empty($post['employeetype'])) {
                    $info['employeeType'][0] = $post['employeetype'];
                }
                if (!isset($post['phone'])) {
                    $info['homephone'][0] = $post['phone'];
                    $info['mobile'][0] = $post['phone'];
                }

                if (!empty($post['password'])) {
                    $info['userpassword'][0] = ldapSha($post['password']);
                }
                $info['title'][0] = "Member";

                $info['objectclass'][0] = "inetOrgPerson";
                $info['objectclass'][1] = "posixAccount";
                $info['objectclass'][2] = "shadowAccount";
                $info['objectclass'][3] = "top";
                $info['loginshell'][0] = "/bin/bash";
                $info['shadowlastchange'][0] = $unixTimeDays;
                $info['shadowFlag'][0] = 0;
                $info['shadowMin'][0] = 0;
                $info['shadowMax'][0] = 99999;
                $info['shadowWarning'][0] = 0;
                $info['shadowInactive'][0] = 99999;
                $info['shadowExpire'][0] = 99999;

                $res = $ldap->editUser($info);
                if (!$res) {
                    return $this->error('修改用户信息失败');
                } else {
                    //删除现有所在的组
                    foreach ($groupList as $groupInfo) {
                        if (is_array($groupInfo['memberuid']) && in_array($post['second_name'], $groupInfo['memberuid'])) {
                            $re = $ldap->delToGroup($post['second_name'], $groupInfo['cn']);
                        }
                    }

                    foreach ($post['group'] as $group) {
                        //更新用户群组信息                       
                        $ret = $ldap->addToGroup($post['second_name'], $group);
                    }

                    //把用户保存到本地
                    $userModel = new adminModel();

                    $userInfo['name'] = $post['id'];
                    $userInfo['nickname'] = $post['display_name'];
                    if (!empty($post['password'])) {
                        $userInfo['password'] = password($post['password']);
                    }
                    //添加用户到本地权限组
                    $userDetail = $userModel->where('name', $post['id'])->find();
                    $userId = 0;
                    if (empty($userDetail)) {
                        if (empty($userInfo['password'])) {
                            $userInfo['password'] = password('123456');
                        }
                        $userModel->allowField(true)->save($userInfo);
                        $userId = $userModel->id;
                    } else {
                        $userModel->allowField(true)->save($userInfo, ['id' => $userDetail['id']]);
                        $userId = $userDetail['id'];
                    }

                    //添加用户到本地组
                    //删除现有分组 
                    Db::name('admin_cate_relation')->where('admin_id', $userId)->delete();
                    foreach ($post['group'] as $group) {
                        $groupModel = new \app\admin\model\AdminCate();
                        //加入本地组    
                        $groupDetail = $groupModel->where('name', $group)->find();
                        $groupId = 0;

                        if (!empty($groupDetail)) {
                            $groupId = $groupDetail['id'];
                        } else {
                            //添加组到本地
                            $groupInfo = array();
                            $groupInfo['name'] = $group;
                            $groupInfo['desc'] = $group;

                            $groupModel->allowField(true)->save($groupInfo);

                            $groupId = $groupModel->id;
                        }

                        $adminCateModel = new \app\admin\model\AdminCateRelation();
                        $adminCateInfo = array();
                        $adminCateInfo['admin_id'] = $userId;
                        $adminCateInfo['admin_name'] = $userInfo['nickname'];
                        $adminCateInfo['cate_id'] = $groupId;
                        $adminCateInfo['cate_status'] = 1;
                        $adminCateModel->allowField(true)->save($adminCateInfo);
                    }

                    return $this->success('修改用户信息成功', 'admin/ldapuser/userList');
                }
            } else {
                //查看详情
                $userInfo = $ldap->find($id);
                if (empty($userInfo)) {
                    return $this->error('修改失败：该用户不存在');
                }

                $option = '';
                //获取用户所在组
                foreach ($groupList as $groupInfo) {
                    if (is_array($groupInfo['memberuid']) && in_array($id, $groupInfo['memberuid'])) {
                        $option .= '<option value="' . $groupInfo['cn'] . '" selected>' . $groupInfo['cn'] . '</option>';
                    } else {
                        $option .= '<option value="' . $groupInfo['cn'] . '">' . $groupInfo['cn'] . '</option>';
                    }
                }
                $this->assign("option", $option);
                $this->assign("userInfo", $userInfo);

                return $this->fetch();
            }
        } else {
            //是新增操作 提交
            if ($this->request->isPost()) {
                $post = $this->request->post();
                //验证  唯一规则： 表名，字段名，排除主键值，主键名
                $validate = new \think\Validate([
                    ['second_name', 'require', '账号为必填字段'],
                    ['display_name', 'require', '姓名为必填字段'],
                    ['email', 'require|email', 'email为必填字段'],
//                    ['group', 'require', '请选择分组'],
                    ['password', 'require', '密码不能为空'],
                ]);
                //验证部分数据合法性
                if (!$validate->check($post)) {
                    $this->error('提交失败：' . $validate->getError());
                }

                //验证用户名是否存在               
                $userInfo = $ldap->find($post['second_name']);
                if (!empty($userInfo) && (isset($userInfo['uid']) && $userInfo['uid'] == $post['second_name']) || (isset($userInfo['cn']) && $userInfo['cn'] == $post['second_name'])) {
                    return $this->error('提交失败：该用户名已存在');
                }

                if (!isset($post['phone'])) {
                    $post['phone'] = " ";
                }

                $unixTimeDays = floor(time() / 86400);

                $info['cn'][0] = $post['display_name'];
                $info['givenName'][0] = $post['second_name'];
                $info['uid'][0] = $post['second_name'];
                $info['description'][0] = $post['display_name'];
                $info['displayName'][0] = $post['display_name'];
//                $info['gecos'][0] = $post['second_name'];
                $info['sn'][0] = $post['second_name'];
                $info['mail'][0] = $post['email'];
                $info['homedirectory'][0] = $post['second_name'];
                $info['employeeType'][0] = empty($post['employeetype']) ? ' ' : $post['employeetype'];

                if (!isset($post['phone']) && !empty($post['phone'])) {
                    $info['homephone'][0] = $post['phone'];
                    $info['mobile'][0] = $post['phone'];
                }

                $info['userpassword'][0] = ldapSha($post['password']);

                $info['gidnumber'] = 0;

                $info['objectclass'][0] = "inetOrgPerson";
                $info['objectclass'][1] = "posixAccount";
                $info['objectclass'][2] = "shadowAccount";
                $info['objectclass'][3] = "top";
                $info['loginshell'][0] = "/bin/bash";
                $info['shadowlastchange'][0] = $unixTimeDays;
                $info['shadowFlag'][0] = 0;
                $info['shadowMin'][0] = 0;
                $info['shadowMax'][0] = 99999;
                $info['shadowWarning'][0] = 0;
                $info['shadowInactive'][0] = 99999;
                $info['shadowExpire'][0] = 99999;
                $info['title'][0] = "Member";

//                $info['postalcode'][0] = '';                
//                $info['st'][0] = $state;
//                $info['street'][0] = (string) $address;                

                $res = $ldap->addUser($info);
//                print_r($res);
                if (!$res) {
                    return $this->error('添加失败');
                } else {
                    if (!empty($post['group'])) {
                        foreach ($post['group'] as $group) {
                            $ret = $ldap->addToGroup($post['second_name'], $group);
                        }
                    }

                    //把用户保存到本地
                    $userModel = new adminModel();

                    $userInfo['name'] = $post['second_name'];
                    $userInfo['nickname'] = $post['display_name'];
                    if (!empty($post['password'])) {
                        $userInfo['password'] = password($post['password']);
                    }
                    //添加用户到本地权限组
                    $userDetail = $userModel->where('name', $post['second_name'])->find();
                    $userId = 0;
                    if (empty($userDetail)) {
                        $userModel->allowField(true)->save($userInfo);
                        $userId = $userModel->id;
                    } else {
                        $userModel->allowField(true)->save($userInfo, ['id' => $userDetail['id']]);
                        $userId = $userDetail['id'];
                    }

                    //添加用户到本地组
                    if (!empty($post['group'])) {
                        foreach ($post['group'] as $group) {
                            $groupModel = new \app\admin\model\AdminCate();
                            //加入本地组    
                            $groupDetail = $groupModel->where('name', $group)->find();
                            $groupId = 0;
                            if (!empty($groupDetail)) {
                                $groupId = $groupDetail['id'];
                            } else {
                                //添加组到本地
                                $groupInfo['name'] = $group;
                                $groupInfo['desc'] = $group;
                                $groupModel->allowField(true)->save($groupInfo);
                                $groupId = $groupModel->id;
                            }
                            $adminCateModel = new \app\admin\model\AdminCateRelation();
                            $adminCateInfo = array();
                            $adminCateInfo['admin_id'] = $userId;
                            $adminCateInfo['admin_name'] = $userInfo['nickname'];
                            $adminCateInfo['cate_id'] = $groupId;
                            $adminCateInfo['cate_status'] = 1;
                            $adminCateModel->allowField(true)->save($adminCateInfo);
                            return $this->success('添加用户成功', 'admin/ldapuser/userList');
                        }
                    }
                }
                //写入日志
//                addlog($userModel->id);
            } else {
                //非提交操作  新增空白页
                $option = '';
                //获取用户所在组
                foreach ($groupList as $groupInfo) {
                    $option .= '<option value="' . $groupInfo['cn'] . '">' . $groupInfo['cn'] . '</option>';
                }
                $this->assign("option", $option);
                return $this->fetch();
            }
        }
    }

    public function delete() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        if (!empty($id)) {
            $ldap = new LdapBase();
            $ret = $ldap->deleteUser($id);

            $groupList = $ldap->groupList();
            if ($groupList != '') {
                foreach ($groupList as $groupDetail) {
                    if ($groupDetail != '' && $groupDetail['memberuid'] != '') {
                        foreach ($groupDetail['memberuid'] as $uid) {
                            $uidArr = explode(',', $uid);
                            $uid = str_replace('uid=', '', $uidArr[0]);
                            if ($uid == $id) {
                                $res = $ldap->delToGroup($uid, $groupDetail['cn']);
                            }
                        }
                    }
                }
            }


            if (!$ret) {
                return $this->error('删除用户信息失败');
            } else {
                //删除本地用户
                Db::name('admin')->where('name', $id)->delete();
                return $this->success('删除用户信息成功', 'admin/ldapuser/userList');
            }
        }
        return $this->error('删除失败，请传正确的参数！');
    }

    /**
     * 在本系统进行禁用处理，然后把人员迁移到旧组织结构
     * @return type
     */
    public function disable() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        if (!empty($id)) {
            //更新用户密码为随机密码
            $info['uid'][0] = $id;
            $info['userpassword'][0] = ldapSha(random_code());

            $ldap = new LdapBase();
            $ldap->editUser($info);

            //更新本地用户状态为禁用状态
            $userModel = new adminModel();
            $userInfo['disable'] = 1;
            $userDetail = $userModel->where('name', $id)->find();
            $userModel->allowField(true)->save($userInfo, ['id' => $userDetail['id']]);

            //迁移用户到其他ou 
            $res = $ldap->renameUserToOld($id);

            if (!$res) {
                return $this->error('禁用ldap用户失败');
            } else {
                return $this->success('禁用ldap用户成功');
            }
        }
        return $this->error('禁用ldap用户失败，请传正确的参数！');
    }

    public function reopen() {
        $id = $this->request->has('id') ? $this->request->param('id') : '';
        if (!empty($id)) {
            //更新本地用户状态为禁用状态为非禁用状态
            $userModel = new adminModel();
            $userInfo['disable'] = 0;
            $userDetail = $userModel->where('name', $id)->find();
            $userModel->allowField(true)->save($userInfo, ['id' => $userDetail['id']]);

            //迁移用户到其他ou   
            $ldap = new LdapBase();
            $res = $ldap->renameUserToOrigin($id);
            
             //初始化密码为123456
            $info['uid'][0] = $id;
            $info['userpassword'][0] = ldapSha('123456');

            $ldap = new LdapBase();
            $ldap->editUser($info);

            if (!$res) {
                return $this->error('解禁ldap用户失败');
            } else {
                return $this->success('解禁ldap用户成功，并初始化密码为：123456');
            }
        }
        return $this->error('解禁ldap用户失败，请传正确的参数！');
    }

    public function updatePass() {
        $uid = $this->request->has('id') ? $this->request->param('id') : '';
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $res = checkPassword($post['password']);

            //验证部分数据合法性
            if ($res['code'] == 0) {
                $this->error('提交失败：' . $res['msg']);
            }
//            $info['cn'][0] = $uid;
            $info['uid'][0] = $uid;
            $info['userpassword'][0] = ldapSha($post['password']);

            $ldap = new LdapBase();
            $res = $ldap->editUser($info);
            if (!$res) {
                return $this->error('修改用户密码失败');
            } else {
                return $this->success('修改用户密码成功');
            }
        } else {
            $this->assign("uid", $uid);
            return $this->fetch();
        }
    }

    public function sync() {
        $ldap = new LdapBase();
        $userList = $ldap->userList();
        foreach ($userList as $user) {
            //把用户保存到本地
            $userModel = new adminModel();

            $userInfo['name'] = $user['uid'];
            $userInfo['nickname'] = $user['displayname'];
            if (!empty($user['userpassword'])) {
                $userInfo['password'] = password($user['userpassword']);
            }

            //添加用户到本地权限组
            $userDetail = $userModel->where('name', $user['uid'])->find();
            $userId = 0;
            if (empty($userDetail)) {
                $userModel->allowField(true)->save($userInfo);
                $userId = $userModel->id;
            } else {
                //如果本地组已经存在这个用户，则不做处理
                continue;
                unset($userInfo['password']);
                $userModel->allowField(true)->save($userInfo, ['id' => $userDetail['id']]);
                $userId = $userDetail['id'];
            }

            //添加用户到本地组
            $grupList = $ldap->groupList();
            //删除现有分组
            Db::name('admin_cate_relation')->where('admin_id', $userId)->delete();
            foreach ($grupList as $group) {
                $groupModel = new \app\admin\model\AdminCate();
                //加入本地组    
                $groupDetail = $groupModel->where('name', $group['cn'])->find();
                $groupId = 0;
                if (!empty($groupDetail)) {
                    $groupId = $groupDetail['id'];
                } else {
                    //添加组到本地
                    $groupInfo['name'] = $group['cn'];
                    $groupInfo['desc'] = $group['description'];
                    $groupModel->allowField(true)->save($groupInfo);
                    $groupId = $groupModel->id;
                }
                //判断这个组里是否有这个人
                foreach ($group['memberuid'] as $uid) {
                    if ($user['uid'] == $uid) {
                        $adminCateModel = new \app\admin\model\AdminCateRelation();
                        $adminCateInfo = array();
                        $adminCateInfo['admin_id'] = $userId;
                        $adminCateInfo['admin_name'] = $userInfo['nickname'];
                        $adminCateInfo['cate_id'] = $groupId;
                        $adminCateInfo['cate_status'] = 1;
                        $adminCateModel->allowField(true)->save($adminCateInfo);
                    }
                }
            }
        }
        return $this->success('信息同步成功', 'admin/ldapuser/synchtml');
    }

    public function synchtml() {
        return $this->fetch();
    }

}
